#include <iostream>
#include <unistd.h>
#include "Sock.hpp"

int main(int argc, const char **argv)
{
    // 选项个数不符合要求
    if(argc != 2)
    {
        exit(1);
    }

    // 获取socket文件描述符
    int listenfd = Sock::Socket();
    if(listenfd < 0)
    {
        exit(2);
    }

    // 绑定端口号
    std::string ip = "0.0.0.0";   // 服务器ip
    uint16_t port = atoi(argv[1]);    // 传输服务器端口号
    if(Sock::Bind(listenfd, ip, port) < 0)
    {
        exit(3);
    }

    // 设置监听状态
    if(Sock::Listen(listenfd, 20) < 0)
    {
        exit(4);
    }

    // 获取对端连接
    std::string cli_ip;
    uint16_t cli_port;
    int connfd = Sock::Accept(listenfd, &cli_ip, &cli_port);
    if(connfd < 0)
    {
        exit(5);
    }

    int opt = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    while(true)
    {
        std::string clientip;
        uint16_t clientport;
        int sockfd = Sock::Accept(listenfd, &clientip, &clientport);
        if(sockfd > 0)
        {
            std::cout << "[" << clientip << ":" << clientport << "]# " << sockfd << std::endl;;
        }

        sleep(10);

        close(sockfd);
        std::cout << sockfd << " closed" << std::endl;
    }

    return 0;
}